package cn.humiao.myserialport;

import android.util.Log;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.BaseApplication;
import android_serialport_api.Global;
import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortFinder;

public class SerialPortUtil {

    private SerialPort serialPort = null;
    private InputStream mInputStream = null;
    private OutputStream outputStream = null;
    private ReceiveThread mReceiveThread = null;
    private boolean isStart = false;

    /**
     * 打开串口，接收数据
     * 通过串口，接收单片机发送来的数据
     */
    public void openSerialPort() {
        try {
            //9600 改 115200     ttyS3 改ttyS4  0-4试一下
            String[] devices = new SerialPortFinder().getAllDevicesPath();
            for (String device : devices) {
                Log.i("xy", "--->  device:" + device);
            }
            serialPort = new SerialPort(new File("/dev/ttyS4"), 115200, 0);
            //调用对象SerialPort方法，获取串口中"读和写"的数据流
            mInputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            isStart = true;
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("xy", "---> openSerialPort error: " + e.toString());
        }
        getSerialPort();
    }

    /**
     * 关闭串口中的输入输出流
     */
    public void closeSerialPort() {
        Log.i("test", "关闭串口");
        try {
            if (mInputStream != null) {
                mInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            isStart = false;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送数据
     * 通过串口，发送数据到单片机
     */
    public void sendSerialPort(String data) {
        try {
            byte[] sendData = DataUtils.HexToByteArr(data);
            outputStream.write(sendData);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("xy", "---> send error: ");
        }
    }

    //    0xfe 0x00 0x01 0x0C 0x01 0xf
    public void sendData(byte[] data) {
        try {
            outputStream.write(data);
            outputStream.flush();
            Toast.makeText(BaseApplication.getInstance(), "sendData success", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.i("xy", "--> sendData: " + e.toString());
            Toast.makeText(BaseApplication.getInstance(), e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getSerialPort() {
        if (mReceiveThread == null) {

            mReceiveThread = new ReceiveThread();
        }
        mReceiveThread.start();
    }

    /**
     * 接收串口数据的线程
     */
    private class ReceiveThread extends Thread {
        @Override
        public void run() {
            super.run();
            read();
        }

        private void read() {
            while (true) {
                try {
                    if (mInputStream == null)
                        return;
                    byte[] buffer = new byte[500];
                    int count;
                    if (mInputStream.available() <= 0) {
                        continue;
                    }
                    Thread.sleep(500);
                    count = mInputStream.read(buffer);
                    if (count > 8) {
                        EventBus.getDefault().post(buffer);
                    }
                } catch (Exception e) {
                    return;
                }
            }
        }
    }

}
